<template>
  <a-card class="task-tabs-card" :body-style="{ padding: 0 }">
    <template #title>
      <div
        v-if="isPublishUser && TaskStatusEnum.draft === taskInfo.taskStatus && !disabled"
        class="flex items-center justify-between"
      >
        <div style="line-height: 32px">
          是否需要审批流程：
          <a-radio-group v-model:value="isNeedApproval" @change="isNeedApprovalChange">
            <a-radio :value="true">需要</a-radio>
            <a-radio :value="false">不需要</a-radio>
          </a-radio-group>
        </div>
        <a-space>
          <a-button
            v-if="isNeedApproval && !taskFlowInfo && !copyFlowTag"
            type="primary"
            @click="refSelectProcess.show()"
            >选择审批流程</a-button
          >
          <template v-if="!copyFlowTag">
            <a-button v-if="taskFlowInfo && isNeedApproval" type="primary" @click="editFlow">编辑</a-button>
            <a-button v-if="taskFlowInfo && isNeedApproval" type="primary" danger @click="deleteFlow">删除</a-button>
          </template>
        </a-space>
      </div>
    </template>
    <template v-if="taskFlowInfo && isNeedApproval">
      <div class="full-card">
        <reviewFlow
          v-if="renderAble"
          style="padding-bottom: 10px"
          :canvas-data="taskFlowInfo.canvas"
          :hide-sign-setting="hideSignSetting"
          :flow-id="taskFlowInfo.taskFlowId"
        />
      </div>
    </template>
    <IcpEmpty v-else />
  </a-card>

  <SelectProcess
    ref="refSelectProcess"
    :task-id="taskInfo.taskId"
    :entry-type="taskInfo.sourceType === 'project' ? 4 : 3"
    :template-type="2"
    :has-search="true"
    :tag="tag"
    :hide-sign-setting="hideSignSetting"
    @submit="refreshData"
  />

  <editFlowVue
    v-if="taskFlowInfo"
    ref="editFlowVueRef"
    :hide-sign-setting="hideSignSetting"
    :task-flow-id="props.taskInfo.sourceType === 'project' ? taskFlowInfo.taskFlowId : taskFlowInfo.speedFlowId"
    :entry-type="taskInfo.sourceType === 'project' ? 4 : 3"
    @updateFlow="refreshData"
  />
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { getTaskFlowDetail, getSopSpeedTaskFlow, remove, ctmsRemove } from '@@/api/flow'
import SelectProcess from './SelectProcess.vue'
import reviewFlow from '@@/components/ReviewFlow/index.vue'
import editFlowVue from './components/editFlow.vue'
import { TaskStatusEnum } from '@@/enums/taskEnum'
import { Modal, message } from 'ant-design-vue'
import { useUserStoreWidthOut } from '@/store/modules/user'
//{ taskInfo, needProcess }
const props = defineProps<{
  taskInfo: any
  needProcess: boolean | undefined | number
  isPublishUser: boolean
  disabled?: boolean
  hideSignSetting?: boolean
  tag?: any
  processKey?: number // 后端转为1 2 4 8 16 32来接收,现在只有药房业务配置使用该方式
  copyFlowTag?: number // 复制其他tag的流程，并不允许修改和删除
}>()

const emits = defineEmits(['resetData'])

const refSelectProcess = ref<any>(null)
const editFlowVueRef = ref<any>(null)
const taskFlowInfo = ref()
const renderAble = ref(true)
const isNeedApproval = ref(
  props.processKey
    ? (Number(props.needProcess || 0) & props.processKey) === props.processKey
    : props.needProcess
    ? true
    : false
)
const userStore: any = useUserStoreWidthOut()

const isNeedApprovalChange = () => {
  const taskId = props.taskInfo.mainId || 'taskId'
  const required = props.taskInfo.isPerNeedFlow || 'required'
  let requiredVal
  if (props.processKey) {
    if ((Number(props.needProcess || 0) & props.processKey) === props.processKey) {
      requiredVal = isNeedApproval.value ? props.needProcess : Number(props.needProcess || 0) - props.processKey
    } else {
      requiredVal = isNeedApproval.value ? Number(props.needProcess || 0) + props.processKey : props.needProcess
    }
  } else {
    requiredVal = isNeedApproval.value
  }
  props.taskInfo
    .updateFlowRequiredApi({
      [taskId]: props.taskInfo.taskId,
      [required]: requiredVal,
      name: props.taskInfo.name,
      orgId: userStore.getOrgId
    })
    .then(() => {
      emits('resetData', requiredVal)
    })
    .catch(() => {
      isNeedApproval.value = props.processKey
        ? (Number(props.needProcess) & props.processKey) === props.processKey
        : props.needProcess
        ? true
        : false
    })
}
onMounted(() => {
  refreshData()
})

const refreshData = (isEmpty?) => {
  renderAble.value = false
  const fn = props.taskInfo.sourceType === 'project' ? getTaskFlowDetail : getSopSpeedTaskFlow
  // getTaskFlow 项目中心端   getSopSpeedTaskFlow 项目进度模板端
  fn({
    taskId: props.taskInfo.taskId,
    tag: props.copyFlowTag || props.tag
  }).then(async (res: any) => {
    if (Object.keys(res).length === 0) {
      taskFlowInfo.value = null
      return
    }
    if (props.taskInfo.sourceType === 'project') {
      const tempData = res
      const canvasData = JSON.parse(tempData.canvas)
      if (
        ![TaskStatusEnum.draft, TaskStatusEnum.pendingSubmission, TaskStatusEnum.pendingFeedback].includes(
          props.taskInfo.taskStatus
        )
      ) {
        if (tempData.taskNodeId) {
          if (!tempData.neverWalkedList) {
            tempData.neverWalkedList = []
          }
          tempData.neverWalkedList.push(tempData.taskNodeId)
        }
        canvasData.nodes.forEach((node: any) => {
          if (
            (tempData.neverWalkedList || []).includes(node.id) &&
            props.taskInfo.taskStatus !== TaskStatusEnum.completed
          ) {
            node.properties.isFinished = false
          } else {
            node.properties.isFinished = true
          }
          if (tempData.taskNodeId === node.id && props.taskInfo.taskStatus !== TaskStatusEnum.completed) {
            node.properties.isCurrentNode = true
          }
        })
        ;(tempData.nextNodeInfoVOList || []).forEach((item: any) => {
          const currNode = canvasData.nodes.find((node: any) => node.id === item.nodeId)
          if (currNode) {
            if (item.approvalParamType === 'PRE') {
              currNode.properties['flowable:candidateUsers'] = item.approvalParamValue.join(',')
              currNode.properties['flowable:candidateUsersName'] = item.approvalParamName
            } else {
              currNode.properties['flowable:candidateGroups'] = item.approvalParamValue.join(',')
              currNode.properties['flowable:candidateGroupsName'] = item.approvalParamName
            }
          }
        })
      }
      tempData.canvas = JSON.stringify(canvasData)
      renderAble.value = true
      taskFlowInfo.value = tempData
    } else {
      renderAble.value = true
      taskFlowInfo.value = res[0]
    }
    if (isEmpty) {
      await nextTick()
      editFlow()
    }
  })
}

// refreshData()

const editFlow = () => {
  editFlowVueRef.value.show()
}

const deleteFlow = () => {
  Modal.confirm({
    title: '是否确认删除？',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      const fn = props.taskInfo.sourceType === 'project' ? ctmsRemove : remove
      fn({
        id: taskFlowInfo.value.taskFlowId || taskFlowInfo.value.speedFlowId,
        entryType: props.taskInfo.sourceType === 'project' ? 4 : 3
      }).then(() => {
        refreshData()
      })
      message.success({
        content: 'ok',
        style: {
          display: 'none'
        }
      })
    },
    onCancel: () => {
      message.success({
        content: 'cancel',
        style: {
          display: 'none'
        }
      })
    }
  })
}
</script>

<style lang="less"></style>
